//
//  WH_CheckViewController.m
//  App_6.23
//
//  Created by wanghao on 16/7/26.
//  Copyright © 2016年 wanghao. All rights reserved.
//

#import "WH_CheckViewController.h"
#import "WH_CheckCell.h"
#import "WH_Home.h"
#import "WH_ListOrder.h"

@interface WH_CheckViewController ()<UITableViewDataSource,UITableViewDelegate,PayPalPaymentDelegate>

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) UILabel *countLabel;
@property (nonatomic, strong) UILabel *tatolLabel;
@property (nonatomic, strong) UILabel *moneyLabel;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) PayPalConfiguration *payPalConfig;
@property (nonatomic, strong) UIButton *labCbtn;
@property (nonatomic, strong) UIButton *labTbtn;
@property (nonatomic, assign) BOOL isYue;
@property (nonatomic, strong) UILabel *labC;
@property (nonatomic, strong) NSDictionary *payDic;
@property (nonatomic, strong) WH_ListOrder *listO;
@end

@implementation WH_CheckViewController

-(void)viewWillAppear:(BOOL)animated{
    
    
    [self.tabBarController.tabBar setHidden:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    
    
    [self.tabBarController.tabBar setHidden:NO];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createLabel];
    [self createTab];
    [self bottomView];
    [self checkView];
    [self postPrice];
    self.dataArr = [NSMutableArray arrayWithArray:_modelArr];
    [PayPalMobile preconnectWithEnvironment:PayPalEnvironmentSandbox];
    [self createPayPal];
    [self createHub];
    [self hubShow];

}
#pragma mark - 余额

-(void)postPrice{
    NSString *body = [NSString stringWithFormat:@"action=account&user_id=%@",NSUSERID];
    [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        
        // NSLog(@"%@",result);
        NSDictionary *dic = result;
        NSDictionary *user_array = [dic objectForKey:@"user_array"];
        NSString *user_price = [user_array objectForKey:@"user_price"];
        _labC.text = [NSString stringWithFormat:@"余额支付(%@)",user_price];
        NSInteger priceUser = [user_price integerValue];
        NSLog(@"%ld",(long)priceUser);
        
        if (_orderPrice > priceUser) {
            
            [_labCbtn setBackgroundImage:[UIImage imageNamed:@"圆形未选中"] forState:UIControlStateNormal];
            _isYue = NO;
            _labCbtn.userInteractionEnabled = NO;
            [_labTbtn setBackgroundImage:[UIImage imageNamed:@"单选 按钮"] forState:UIControlStateNormal];
        }else{
            
            _isYue = YES;
            [_labCbtn setBackgroundImage:[UIImage imageNamed:@"单选 按钮"] forState:UIControlStateNormal];
            [_labTbtn setBackgroundImage:[UIImage imageNamed:@"圆形未选中"] forState:UIControlStateNormal];

        }
        
        [self hubDismiss];
    } failure:^(NSError *error) {
        
        
    }];
    
    
}


#pragma mark - 结算生成订单 POST

-(void)postOrder:(NSString *)payID payKey:(NSString *)key total:(NSInteger)total code:(NSDictionary *)code{
    
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    
    [para setObject:@"checkout" forKey:@"action"];
    [para setObject:NSUSERID forKey:@"user_id"];
    [para setObject:key forKey:@"pay_key"];
    [para setObject:payID forKey:@"pay_id"];
    [para setObject:[NSString stringWithFormat:@"%ld",(long)total] forKey:@"total"];
    if (code.count != 0) {
        
        [para setObject:code forKey:@"pay_code"];
    }
    

    [WH_AppTools postUrl:URLstr body:para result:HXJSON requestStyle:HXRequestDic headerFile:nil success:^(id result) {
        
        NSLog(@"%@",result);
        NSDictionary *dic = result;
        NSString *status = [dic objectForKey:@"status"];
        NSString *message = [dic objectForKey:@"message"];
        if ([status isEqualToString:@"success"]) {
            [WSProgressHUD showImage:nil status:status maskType:(WSProgressHUDMaskTypeClear)];
            [self deleOrder];
        }else{
            
            [WSProgressHUD showImage:nil status:message maskType:WSProgressHUDMaskTypeClear];
        }
        
    } failure:^(NSError *error) {
        
        
    }];
    
    
}


-(void)createLabel{
    
    self.countLabel = [UILabel new];
    _countLabel.backgroundColor = [UIColor whiteColor];
    _countLabel.font = [UIFont systemFontOfSize:14.f];
    _countLabel.text = [NSString stringWithFormat:@"    共%ld件产品",_orderCount];
    [self.view addSubview:_countLabel];
    [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(@0);
        make.top.mas_equalTo(@0);
        make.height.mas_equalTo(@40);
        make.width.mas_equalTo(SCREEN_WIDTH/2);
    }];
    
    self.tatolLabel = [UILabel new];
    _tatolLabel.backgroundColor = [UIColor whiteColor];
    _tatolLabel.font = [UIFont systemFontOfSize:14.f];
    _tatolLabel.textAlignment = NSTextAlignmentRight;
    _tatolLabel.text = [NSString stringWithFormat:@"%ld夺宝币",_orderPrice];
    _tatolLabel.textColor = [UIColor redColor];
    [self.view addSubview:_tatolLabel];
    [self.tatolLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(@-10);
        make.top.height.width.equalTo(self.countLabel);
    }];

    UILabel *label = [UILabel new];
    label.backgroundColor = [UIColor colorWithRed:0.67 green:0.67 blue:0.67 alpha:1];
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(@0);
        make.top.equalTo(self.countLabel.mas_bottom);
        make.height.mas_equalTo(@1);
    }];
    
    
}

-(void)checkView{
    
    UIView *checkView = [UIView new];
    checkView.tag = 30011;
    [self.view addSubview:checkView];
    checkView.backgroundColor = [UIColor whiteColor];
    [checkView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.mas_equalTo(@0);
        make.bottom.mas_equalTo(-49);
        make.height.mas_equalTo(49);
    }];

    self.labC = [UILabel new];
    _labC.text = @"余额支付";
    _labC.font = [UIFont systemFontOfSize:15.f];
    [checkView addSubview:_labC];
    [_labC mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(@20);
        make.top.equalTo(@6);
        make.bottom.mas_equalTo(@-6);
        make.width.mas_equalTo(SCREEN_WIDTH/3);
        
    }];
    self.labCbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [_labCbtn addTarget:self action:@selector(labCbtn:) forControlEvents:UIControlEventTouchUpInside];

    [checkView addSubview:_labCbtn];
    [_labCbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(_labC.mas_right).offset(5);
        make.centerY.equalTo(_labC);
        make.width.height.equalTo(_labC.mas_height).multipliedBy(0.4);
    }];
    
    
    UILabel *labT = [UILabel new];
    labT.text = @"PayPal支付";
    labT.font = [UIFont systemFontOfSize:15.f];
    [checkView addSubview:labT];
    [labT mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.mas_equalTo(@-50);
        make.top.bottom.equalTo(_labC);
        make.width.mas_equalTo(SCREEN_WIDTH/4);
    }];

    self.labTbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_labTbtn addTarget:self action:@selector(labTbtn:) forControlEvents:UIControlEventTouchUpInside];
    [checkView addSubview:_labTbtn];
    [_labTbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(@-20);
        make.centerY.equalTo(labT);
        make.width.height.equalTo(labT.mas_height).multipliedBy(0.4);
    }];

    UIView *line = [UIView new];
    [checkView addSubview:line];
    line.backgroundColor = [UIColor colorWithRed:0.86 green:0.85 blue:0.86 alpha:1];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.top.mas_equalTo(@0);
        make.height.mas_equalTo(@1);
    }];
}

#pragma mark - Button
-(void)labCbtn:(UIButton *)btnC{
    
    _isYue = YES;
    [_labTbtn setBackgroundImage:[UIImage imageNamed:@"圆形未选中"] forState:UIControlStateNormal];
    [btnC setBackgroundImage:[UIImage imageNamed:@"单选 按钮"] forState:UIControlStateNormal];

}

-(void)labTbtn:(UIButton *)btnT{
    
    _isYue = NO;
    [btnT setBackgroundImage:[UIImage imageNamed:@"单选 按钮"] forState:UIControlStateNormal];
    [_labCbtn setBackgroundImage:[UIImage imageNamed:@"圆形未选中"] forState:UIControlStateNormal];

}

-(void)bottomView{
    
    UIView *bottomView = [UIView new];
    bottomView.tag = 20011;
    [self.view addSubview:bottomView];
    bottomView.backgroundColor = [UIColor whiteColor];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.mas_equalTo(@0);
        make.bottom.mas_equalTo(@0);
        make.height.mas_equalTo(49);
    }];
    
    self.moneyLabel = [UILabel new];
    NSString *str = [NSString stringWithFormat:@"%ld元",(long)_orderPrice];
    _moneyLabel.text = [NSString stringWithFormat:@"实付款:  %@",str];
    [WH_AppTools changeColor:_moneyLabel.text color:[UIColor redColor] xx:str nn:_moneyLabel];
    [bottomView addSubview:_moneyLabel];
    [_moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(@20);
        make.top.equalTo(@6);
        make.bottom.mas_equalTo(@-6);
        make.width.mas_equalTo(SCREEN_WIDTH/2);
    }];
    
    UIView *line = [UIView new];
    [bottomView addSubview:line];
    line.backgroundColor = [UIColor colorWithRed:0.86 green:0.85 blue:0.86 alpha:1];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.top.mas_equalTo(@0);
        make.height.mas_equalTo(@1);
    }];
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.backgroundColor = [UIColor redColor];
    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addBtn setTitle:@"提交" forState:UIControlStateNormal];
    [bottomView addSubview:addBtn];
    [addBtn addTarget:self action:@selector(subOrder:) forControlEvents:UIControlEventTouchUpInside];
    
    [addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(@6);
        make.bottom.equalTo(@-6);
        make.right.mas_equalTo(@-10);
        make.width.equalTo(@(SCREEN_WIDTH/3-9));
    }];
    
}
#pragma mark - 支付

-(void)subOrder:(UIButton *)btn{
    
    
    if (_isYue == YES) {
        
        [self alertViewControllerWithTitle:@"确认余额支付吗?" content:@"" block:^{
            
            [self postTatolallpayment:@"1"];
            
        }];
    }else if (_isYue == NO){
        
        
        [self postTatolallpayment:@"0"];
    }
    
    
}
#pragma mark - PayPal

-(void)createPayPal{
    
    _payPalConfig = [[PayPalConfiguration alloc] init];
    //是否接受信用卡
    _payPalConfig.acceptCreditCards = YES;
    
    //商家名称
    _payPalConfig.merchantName = @"HZL";
    //paypal账号下的地址信息
    _payPalConfig.payPalShippingAddressOption = PayPalShippingAddressOptionNone;
    
    //配置语言环境
    _payPalConfig.languageOrLocale = [NSLocale preferredLanguages][0];
    NSLog(@"PayPal iOS SDK version: %@", [PayPalMobile libraryVersion]);

    
}
#pragma mark - paypal支付

-(void)CreatePayment{
    
    PayPalPayment *payment = [[PayPalPayment alloc] init];
    
    //订单总额
    payment.amount = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%ld",(long)_orderPrice]];
    
    //货币类型-RMB是没用的
    payment.currencyCode = @"USD";
    
    //订单描述
    payment.shortDescription = @"Cart Total";
    //生成paypal控制器，并模态出来(push也行)
    //将之前生成的订单信息和paypal配置传进来，并设置订单VC为代理
    PayPalPaymentViewController *paymentViewController = [[PayPalPaymentViewController alloc] initWithPayment:payment                                                                                           configuration:self.payPalConfig                                                                                          delegate:self];
    
    //模态展示
    [self presentViewController:paymentViewController animated:YES completion:nil];
    
    
}
//订单支付完成后回调此方法
- (void)payPalPaymentViewController:(PayPalPaymentViewController *)paymentViewController didCompletePayment:(PayPalPayment *)completedPayment {
    NSLog(@"PayPal Payment Success!");
    
    [self postOrder:_listO.pay_id payKey:_listO.pay_key total:_orderPrice code:completedPayment.confirmation];

    
}

//用户取消支付回调此方法
- (void)payPalPaymentDidCancel:(PayPalPaymentViewController *)paymentViewController {
    NSLog(@"PayPal Payment Canceled");
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}

-(void)postTatolallpayment:(NSString *)payment{
    
    NSString *body = [NSString stringWithFormat:@"action=payment&user_id=%@&cart_total=%ld&allpayment=%@", NSUSERID,(long)_orderPrice, payment];
    
    
    
    [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        
        NSLog(@"%@",result);
        NSDictionary *dic = result;
        NSString *status = [dic objectForKey:@"status"];
        NSString *message = [dic objectForKey:@"message"];
        NSDictionary *payment_array = [dic objectForKey:@"payment_array"];
        if ([payment isEqualToString:@"1"]) {
            
            NSDictionary *SITEDic = [payment_array objectForKey:@"SITE"];
            _payDic = [NSDictionary dictionaryWithDictionary:SITEDic];
        }else{
            
            NSDictionary *PAYPALDic = [payment_array objectForKey:@"PAYPAL"];
            _payDic = [NSDictionary dictionaryWithDictionary:PAYPALDic];
        }
        
        self.listO = [WH_ListOrder modelWithDictionary:_payDic];
        if ([status isEqualToString:@"success"]) {
            if ([payment isEqualToString:@"1"]) {
                
                [self postOrder:_listO.pay_id payKey:_listO.pay_key total:_orderPrice code:nil];

            }else{
                
                [self CreatePayment];
            }
            
        }else{
            
            [WSProgressHUD showImage:nil status:message];
            
        }
        
    } failure:^(NSError *error) {
        
        
    }];
    
}
-(void)deleOrder{
    
    for (WH_Home *periodH in self.dataArr) {
        
        NSString *body = [NSString stringWithFormat:@"action=cart_del&user_id=%@&product_period=%@", NSUSERID,periodH.product_period];
        [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
            
            // NSLog(@"%@",result);
            NSDictionary *dic = result;
            NSString *status = [dic objectForKey:@"status"];
            NSString *message = [dic objectForKey:@"message"];
            if ([status isEqualToString:@"success"]) {
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    [self dismissViewControllerAnimated:YES completion:^{
                        
                    }];

                    
                });
            }else{
                
                [WSProgressHUD showImage:nil status:message];
                
            }
            
        } failure:^(NSError *error) {
            
            
        }];

    }
}
-(void)createTab{
    
    self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.rowHeight = 70;
    self.myTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_myTableView];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(@0);
        make.top.mas_equalTo(@41);
        
    }];
    //自定义cell Xib注册
    [self.myTableView registerNib:[UINib nibWithNibName:@"WH_CheckCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"CheckCell"];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *chect = @"CheckCell";
    WH_CheckCell *cell = [tableView dequeueReusableCellWithIdentifier:chect];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.list = self.dataArr[indexPath.row];
    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
